<!--
  * 设备模板列表
-->
<template>
  <div>
    <!---------- 表格操作行 begin ----------->
    <a-row class="flex justify-between items-center m-b-2">
      <div class="">
        <group-title :iconOptions="{ class: 'text-blue-400' }">{{ props.type == 0 ? '播报模板' : '打印模板' }}</group-title>
      </div>
      <div class="" v-if="props.formType != 'view'">
        <!-- <TableOperator v-model="columns" :tableId="null" :refresh="queryData" /> -->
        <a-button type="primary" size="small" @click="addItem"> 新增</a-button>
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->

    <!---------- 表格 begin ----------->

    <a-form ref="formRef" :model="formData" :rules="rules" :disabled="props.formType == 'view'" layout="vertical">
      <a-table
        size="small"
        :dataSource="tableData"
        :columns="columns.filter((e) => !e.hidden)"
        rowKey="id"
        bordered
        :loading="tableLoading"
        :pagination="false"
        :scroll="{ x: 'max-content' }"
      />
    </a-form>
    <!---------- 表格 end ----------->

    <div class="smart-query-table-page">
      <a-pagination
        showSizeChanger
        showQuickJumper
        show-less-items
        :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :defaultPageSize="queryForm.pageSize"
        v-model:current="queryForm.pageNo"
        v-model:pageSize="queryForm.pageSize"
        :total="total"
        @change="queryData"
        @showSizeChange="queryData"
        :show-total="(total) => `共${total}条`"
      />
    </div>
  </div>
</template>
<script setup>
  import { reactive, ref, onMounted, computed, getCurrentInstance, h, toRefs, watch } from 'vue'
  import { Button, Switch, Modal, message, FormItem, Input, InputNumber, RadioGroup } from 'ant-design-vue'
  import { cloneDeep, isEmpty } from 'lodash'
  import { SmartLoading } from '/@/components/framework/smart-loading'
  import { deviceModuleDetailApi } from '/@/api/business/b-operation/device-module-detail'
  import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const'
  import { privilege } from '/@/utils/common'
  import { selectDictLabel } from '/@/utils/common'
  import dayjs from 'dayjs'
  import {
    DEVICE_TYPE, // 通道业务类型
  } from '/@/constants/dict'

  // console.log('useUserStore===>', useUserStore().userInfo)
  const { proxy } = getCurrentInstance()

  // ---------------------------- 表格列 ----------------------------
  const props = defineProps({
    formType: {
      type: String,
      default: 'update',
    },
    type: {
      type: Array,
      default: 0,
    },
    rowData: {
      type: Object,
      default: () => {},
    },
  })

  const columns = ref([
    {
      title: props.type == '0' ? '播报模板名称' : '打印模板名称',
      dataIndex: 'name',
      customRender: ({ record, text, index }) => {
        return record.isEdit
          ? h(
              FormItem,
              {
                name: ['tableData', index, 'name'],
              },
              [
                h(Input, {
                  placeholder: '请输入',
                  value: tableData.value[index].name,
                  'onUpdate:value': (value) => {
                    tableData.value[index].name = value
                  },
                }),
              ],
            )
          : text
      },
      ellipsis: true,
    },
    {
      title: props.type == '0' ? '播报内容' : '打印内容',
      dataIndex: 'content',
      width: 380,
      customRender: ({ record, text, index }) => {
        return record.isEdit
          ? h(
              FormItem,
              {
                name: ['tableData', index, 'content'],
              },
              [
                h(Input, {
                  placeholder: '请输入',
                  value: tableData.value[index].content,
                  'onUpdate:value': (value) => {
                    tableData.value[index].content = value
                  },
                }),
              ],
            )
          : text
      },
      ellipsis: true,
    },
    {
      title: '金额读取',
      dataIndex: 'retain',
      hidden: props.type == '1',
      customRender: ({ record, text, index }) => {
        return record.isEdit
          ? h(
              FormItem,
              {
                name: ['tableData', index, 'retain'],
              },
              [
                h(RadioGroup, {
                  options: [
                    { label: '播报读0', value: 1 },
                    { label: '播报不读0', value: 0 },
                  ],
                  value: tableData.value[index].retain,
                  'onUpdate:value': (value) => {
                    tableData.value[index].retain = value
                  },
                }),
              ],
            )
          : text == 0
            ? '播报不读0'
            : '播报读0'
      },
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      customRender: ({ record, text }) => {
        return h('div', [
          h(Switch, {
            checked: text,
            checkedValue: 1,
            unCheckedValue: 0,
            onChange: (checked) => {
              if (record.isDefault == 1) {
                return message.error('默认模板不能禁用')
              }
              changeStatus(checked, record)
            },
          }),
        ])
      },
      ellipsis: true,
    },
    {
      title: '是否为默认',
      dataIndex: 'isDefault',
      customRender: ({ record, text }) => {
        return h('div', [
          h(Switch, {
            checked: text,
            checkedValue: 1,
            unCheckedValue: 0,
            onChange: (checked) => {
              if (record.status == 0) {
                return message.error('停用模板不能设置默认')
              }
              changeIsDefault(checked, record)
            },
          }),
        ])
      },
      width: 180,
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      minWidth: 180,
      hidden: props.formType == 'view',
      customRender: ({ record, index }) => {
        return h('div', [
          !record.isEdit
            ? h(
                Button,
                {
                  type: 'link',
                  size: 'small',
                  onClick: () => {
                    if (record.isDefault == 1) {
                      return message.error('默认设备不能修改')
                    }
                    record.isEdit = true
                  },
                },
                '修改',
              )
            : '',
          record.isEdit
            ? h(
                Button,
                {
                  type: 'link',
                  size: 'small',
                  onClick: () => {
                    onSubmit().then((e) => {
                      if (e) {
                        save(record)
                        record.isEdit = false
                      }
                    })
                  },
                },
                '保存',
              )
            : '',
          h(
            Button,
            {
              type: 'link',
              size: 'small',
              onClick: () => {
                if (record.isDefault == 1) {
                  return message.error('默认设备不能删除')
                }
                if (record.id) {
                  Modal.confirm({
                    title: '提示',
                    content: '确定要删除该数据吗?',
                    okText: '删除',
                    okType: 'danger',
                    async onOk() {
                      rowDelete(record)
                    },
                    cancelText: '取消',
                    onCancel() {},
                  })
                } else {
                  delItem(index)
                }
              },
            },
            '删除',
          ),
        ])
      },
    },
  ])

  // ---------------------------- 查询数据表单和方法 ----------------------------

  const queryFormState = {
    deviceType: undefined,
    dmId: undefined,
    pageNo: 1,
    pageSize: 10,
  }
  // 查询表单form
  const queryForm = ref({ ...queryFormState })
  // 表格加载loading
  const tableLoading = ref(false)
  // 表格数据
  // const tableData = ref([])
  // 总数
  const total = ref(0)

  // 查询数据
  async function queryData() {
    tableLoading.value = true
    try {
      let queryResult = await deviceModuleDetailApi.page(queryForm.value)
      tableData.value = queryResult.data.map((item) => ({
        ...item,
        isEdit: false,
      }))
      total.value = queryResult.total
    } catch (e) {
      console.log(e)
    } finally {
      tableLoading.value = false
    }
  }

  const formData = reactive({
    tableData: [],
  })
  const { tableData } = toRefs(formData)
  const formRef = ref()
  const rules = ref({
    tableData: computed(() => {
      let arr = []
      if (tableData.value && tableData.value.length > 0) {
        arr = tableData.value.map((item) => {
          return {
            name: [{ required: true, message: '型号名称 必填' }],
            content: [{ required: true, message: '播报内容 必填' }],
            retain: [{ required: true, message: '金额读取 必填' }],
          }
        })
      }
      return arr
    }),
  })
  // 点击确定，验证表单
  async function onSubmit() {
    let isValid = false
    try {
      await formRef.value.validateFields()
      isValid = true
    } catch (err) {
      message.warning(err.errorFields[0].errors)
      isValid = false
    }
    return isValid
  }

  // 新建、编辑API
  async function save(paramet) {
    SmartLoading.show()
    try {
      let data = { ...paramet }
      if (data.id) {
        await deviceModuleDetailApi.update(data)
      } else {
        await deviceModuleDetailApi.insert(data)
      }
      message.success('操作成功')

      queryData()
    } catch (err) {
      console.error(err)
    } finally {
      SmartLoading.hide()
    }
  }

  // 切换状态
  const changeStatus = async (status, row) => {
    Modal.confirm({
      title: '提示',
      content: '确定要修改该状态吗?',
      okText: '确定',
      async onOk() {
        let data = {
          id: row.id,
          status: status,
          deviceType: props.type,
        }
        deviceModuleDetailApi.updateStatus(data).then((res) => {
          if (res.code == 200) {
            message.success('修改成功')
            queryData()
          } else {
            message.error(res.msg)
          }
        })
      },
      cancelText: '取消',
      onCancel() {},
    })
  }
  // 切换默认
  const changeIsDefault = async (val, row) => {
    Modal.confirm({
      title: '提示',
      content: '确定要将这个模板修改为默认吗?',
      okText: '确定',
      async onOk() {
        let data = {
          id: row.id,
          isDefault: val,
          dmId: props.rowData.id,
          deviceType: props.type,
        }
        deviceModuleDetailApi.updateIsDefault(data).then((res) => {
          if (res.code == 200) {
            message.success('修改成功')
            queryData()
          } else {
            message.error(res.msg)
          }
        })
      },
      cancelText: '取消',
      onCancel() {},
    })
  }

  const tableItem = {
    isEdit: true,
    retain: 0,
    dmId: props.rowData.id,
    deviceType: props.type,
  }
  /* 增删行 */
  const addItem = () => {
    const newRow = tableData.value.some((item) => isEmpty(item.id))
    console.log('newRow', newRow)

    if (newRow) {
      message.error('请先保存当前行')
      return
    }
    tableData.value.push({ ...cloneDeep(tableItem) })
  }
  const delItem = (index) => {
    if (tableData.value.length <= 1) {
      return message.error('模板不能少于一个!')
    }
    tableData.value.splice(index, 1)
  }
  //请求删除
  async function rowDelete(record) {
    try {
      SmartLoading.show()
      await deviceModuleDetailApi.delete({ id: record.id })
      message.success('删除成功')
      queryData()
    } catch (e) {
      console.log(e)
    } finally {
      SmartLoading.hide()
    }
  }
  /* 增删行 */

  watch(
    [() => props.rowData, props.type],
    (val) => {
      if (props.rowData) {
        queryForm.value.deviceType = props.type
        queryForm.value.dmId = props.rowData.id
        queryData()
      }
    },
    { immediate: true },
  )
</script>
